package org.proteored.miapeapi.xml.gelml;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.proteored.miapeapi.exceptions.IllegalMiapeArgumentException;
import org.proteored.miapeapi.exceptions.MiapeDatabaseException;
import org.proteored.miapeapi.exceptions.MiapeSecurityException;
import org.proteored.miapeapi.exceptions.WrongXMLFormatException;
import org.proteored.miapeapi.interfaces.ge.MiapeGEDocument;
import org.proteored.miapeapi.interfaces.persistence.PersistenceManager;
import org.proteored.miapeapi.xml.gelml.autogenerated.GelMLGelMLRootGelMLType;

public class GEMiapeFactory {
	private static GEMiapeFactory instance;

	private GEMiapeFactory() {	
	}

	public static GEMiapeFactory getFactory() {
		if (instance == null) {
			instance = new GEMiapeFactory();
		}
		return instance;
	}

	public MiapeGEDocument create(MiapeGelMLFile xmlFile, PersistenceManager databaseManager, String user, String password) throws MiapeDatabaseException, MiapeSecurityException, IllegalMiapeArgumentException {
		MiapeGEDocument result = null;
		try {
			JAXBContext jc = JAXBContext.newInstance("org.proteored.miapeapi.xml.gelml.autogenerated" );
			Unmarshaller unmarshaller = jc.createUnmarshaller();

			JAXBElement<GelMLGelMLRootGelMLType> xmlElement = (JAXBElement<GelMLGelMLRootGelMLType>)unmarshaller.unmarshal(xmlFile.toFile());
			GelMLGelMLRootGelMLType gelML = xmlElement.getValue();

			if (databaseManager == null) {
				result = new GEDocumentFromgelML(gelML, null);
			} else {
				result = new GEDocumentFromgelML(gelML, databaseManager, user, password);
			}
		} catch (JAXBException e) {
			e.printStackTrace();
			throw new WrongXMLFormatException("The file does not seem to have mzIndent format");
		} catch (Exception e) {
			e.printStackTrace();
			throw new WrongXMLFormatException(e);
		}

		return result;
	}

}
